﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TMDT_Nhom1A.BUS;
using TMDT_Nhom1A.DTO;
using System.IO;

namespace TMDT_Nhom1A.Manager
{
    public partial class ChiTietSanPham_Manager : System.Web.UI.Page
    {
        private static int ParentCatalogueID = 0;
        private static int ChildCatalogueID = 0;
        private static ElectricDevice_DTO electricdevice;
        private static List<COUPON> ListCoupon = new List<COUPON>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ElectricDevice_BUS.CatalogueIDOfElectricDevice(Request.QueryString["ElectricDeviceID"], ref ParentCatalogueID, ref ChildCatalogueID);
                List<ElectricDevice_DTO> list = ElectricDevice_BUS.DetailElectricDevice(Request.QueryString["ElectricDeviceID"]);
                dldetailproduct.DataSource = list;
                dldetailproduct.DataBind();
                if (list.Count > 0)
                    electricdevice = list[0];
                BindData();
            }
        }

        private void BindData()
        {
            ListCoupon = Coupon_BUS.ListCouponByElectricDeviceID(Request.QueryString["ElectricDeviceID"]);
            gvcoupondevice.DataSource = ListCoupon;
            gvcoupondevice.DataBind();
        }

        protected void gvcoupondevice_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lbStatus = (Label)e.Row.FindControl("lbstatus");
                Label lbinformation = (Label)e.Row.FindControl("lbinformation");
                LinkButton lbselectcoupon = (LinkButton)e.Row.FindControl("lbselectcoupon");
                if (lbStatus.Text == "1")
                {
                    lbselectcoupon.Visible = true;
                    lbinformation.Text = "Còn hạn";
                }
                else
                {
                    lbselectcoupon.Visible = false;
                    lbinformation.Text = "Hết hạn";
                }
            }
        }

        protected void gvcoupondevice_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CheckAll")
            {
                CheckBox cbcheckall = (CheckBox)gvcoupondevice.HeaderRow.FindControl("cbCheckAll");
                if (cbcheckall.Checked == true)
                {
                    for (int i = 0; i < gvcoupondevice.Rows.Count; i++)
                    {
                        CheckBox cbcheck = (CheckBox)gvcoupondevice.Rows[i].FindControl("cbcheck");
                        cbcheck.Checked = false;
                        cbcheckall.Checked = false;
                    }
                }
                else
                {
                    for (int i = 0; i < gvcoupondevice.Rows.Count; i++)
                    {
                        CheckBox cbcheck = (CheckBox)gvcoupondevice.Rows[i].FindControl("cbcheck");
                        cbcheck.Checked = true;
                        cbcheckall.Checked = true;
                    }
                }
            }
            if (e.CommandName == "SelectCoupon")
            {
                COUPON coupon = Coupon_BUS.DetailCoupon(e.CommandArgument.ToString());
                lbcouponid.Text = coupon.Coupon_ID;
                tbdate.Text = coupon.Date.ToString();
                tbtimetostartselling.Text = coupon.TimeToStartSelling.ToString();
                tbtimetoendselling.Text = coupon.TimeToEndSelling.ToString();
                tbtimetostartusing.Text = coupon.TimeToStartUsing.ToString();
                tbtimetoendusing.Text = coupon.TimeToEndUsing.ToString();
                tbdiscountprice.Text = coupon.DiscountPrice.ToString();
                tbnondiscountprice.Text = coupon.NonDiscountPrice.ToString();
                tbquantityfordiscountprice.Text = coupon.QuantityForDiscountPrice.ToString();
                tbdescription.Text = coupon.Description;
                tbusingcondition.Text = coupon.UsingCondition;
                btaddcoupon.Visible = false;
                btupdate.Visible = true;
                btcancel.Visible = true;
            }
        }

        protected void btactive_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvcoupondevice.Rows.Count; i++)
            {
                CheckBox cbcheck = (CheckBox)gvcoupondevice.Rows[i].FindControl("cbcheck");
                if (cbcheck.Checked == true)
                {
                    LinkButton lbselectcoupon = (LinkButton)gvcoupondevice.Rows[i].FindControl("lbselectcoupon");
                    Coupon_BUS.UpdateStatusCoupon(lbselectcoupon.CommandArgument, 1);
                }
            }
            BindData();
        }

        protected void btdisactive_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvcoupondevice.Rows.Count; i++)
            {
                CheckBox cbcheck = (CheckBox)gvcoupondevice.Rows[i].FindControl("cbcheck");
                if (cbcheck.Checked == true)
                {
                    LinkButton lbselectcoupon = (LinkButton)gvcoupondevice.Rows[i].FindControl("lbselectcoupon");
                    Coupon_BUS.UpdateStatusCoupon(lbselectcoupon.CommandArgument, 0);
                }
            }
            BindData();
        }

        protected void btaddcoupon_Click(object sender, ImageClickEventArgs e)
        {

            COUPON coupon = new COUPON();
            coupon.ElectricDevice_ID = electricdevice.ElectricDevice_ID;
            if (tbdate.Text != "")
                coupon.Date = DateTime.Parse(tbdate.Text);
            if (tbtimetostartselling.Text != "")
                coupon.TimeToStartSelling = DateTime.Parse(tbtimetostartselling.Text);
            if (tbtimetoendselling.Text != "")
                coupon.TimeToEndSelling = DateTime.Parse(tbtimetoendselling.Text);
            if (tbtimetostartusing.Text != "")
                coupon.TimeToStartUsing = DateTime.Parse(tbtimetostartusing.Text);
            if (tbtimetoendusing.Text != "")
                coupon.TimeToEndUsing = DateTime.Parse(tbtimetoendusing.Text);
            if (tbquantityfordiscountprice.Text != "")
                coupon.QuantityForDiscountPrice = int.Parse(tbquantityfordiscountprice.Text);
            coupon.DiscountPrice = tbdiscountprice.Text;
            coupon.NonDiscountPrice = tbnondiscountprice.Text;
            coupon.Description = tbdescription.Text;
            coupon.UsingCondition = tbusingcondition.Text;
            if (tbdate.Text != "" && tbtimetostartselling.Text != "" && tbtimetoendselling.Text != "" && tbtimetostartusing.Text != "" && tbtimetoendusing.Text != "" && tbquantityfordiscountprice.Text != "" && coupon.TimeToStartSelling < coupon.TimeToEndSelling && coupon.TimeToStartUsing < coupon.TimeToEndUsing && coupon.TimeToStartUsing >= coupon.TimeToStartSelling && tbdiscountprice.Text != "" && tbnondiscountprice.Text != "" && coupon.QuantityForDiscountPrice > 0)
            {
                Coupon_BUS.InsertCoupon(coupon);
                BindData();
                btcancel_Click(sender, e);
            }
            else
            {
                lbinformationerro.Text = "Vui lòng kiểm tra ngày nhập có chính xác không ! (ngày hết > ngày bắt đầu, ngày sử dụng >= ngày bán, giá và số lượng)";
                lbinformationerro.Visible = false;
            }

        }

        protected void btupdate_Click(object sender, ImageClickEventArgs e)
        {
            COUPON coupon = new COUPON();
            coupon.Coupon_ID = lbcouponid.Text;
            coupon.ElectricDevice_ID = electricdevice.ElectricDevice_ID;
            if (tbdate.Text != "")
                coupon.Date = DateTime.Parse(tbdate.Text);
            if (tbtimetostartselling.Text != "")
                coupon.TimeToStartSelling = DateTime.Parse(tbtimetostartselling.Text);
            if (tbtimetoendselling.Text != "")
                coupon.TimeToEndSelling = DateTime.Parse(tbtimetoendselling.Text);
            if (tbtimetostartusing.Text != "")
                coupon.TimeToStartUsing = DateTime.Parse(tbtimetostartusing.Text);
            if (tbtimetoendusing.Text != "")
                coupon.TimeToEndUsing = DateTime.Parse(tbtimetoendusing.Text);
            if (tbquantityfordiscountprice.Text != "")
                coupon.QuantityForDiscountPrice = int.Parse(tbquantityfordiscountprice.Text);
            coupon.DiscountPrice = tbdiscountprice.Text;
            coupon.NonDiscountPrice = tbnondiscountprice.Text;
            coupon.Description = tbdescription.Text;
            coupon.UsingCondition = tbusingcondition.Text;
            if (tbdate.Text != "" && tbtimetostartselling.Text != "" && tbtimetoendselling.Text != "" && tbtimetostartusing.Text != "" && tbtimetoendusing.Text != "" && tbquantityfordiscountprice.Text != "" && coupon.TimeToStartSelling < coupon.TimeToEndSelling && coupon.TimeToStartUsing < coupon.TimeToEndUsing && coupon.TimeToStartUsing >= coupon.TimeToStartSelling && tbdiscountprice.Text != "" && tbnondiscountprice.Text != "" && coupon.QuantityForDiscountPrice > 0)
            {
                Coupon_BUS.UpdateCoupon(coupon);
                BindData();
                btcancel_Click(sender, e);
                lbinformationerro.Visible = false;
            }
            else
            {
                lbinformationerro.Text = "Vui lòng kiểm tra ngày nhập có chính xác không ! (ngày hết > ngày bắt đầu, ngày sử dụng >= ngày bán, giá và số lượng)";
                lbinformationerro.Visible = true;
            }

        }

        protected void btcancel_Click(object sender, ImageClickEventArgs e)
        {
            tbdate.Text = "";
            lbcouponid.Text = "";
            tbtimetostartselling.Text = "";
            tbtimetoendselling.Text = "";
            tbtimetostartusing.Text = "";
            tbtimetoendusing.Text = "";
            tbdiscountprice.Text = "";
            tbnondiscountprice.Text = "";
            tbquantityfordiscountprice.Text = "";
            tbdescription.Text = "";
            tbusingcondition.Text = "";
            btaddcoupon.Visible = true;
            btupdate.Visible = false;
            btcancel.Visible = false;
        }

        protected void dldetailproduct_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "btEditProduct")
            {

                pncatalogue.Visible = true;
                dlparentcatalogue.DataSource = ParentCatalogue_BUS.ListKeyCatalogue();
                dlparentcatalogue.DataValueField = "ParentCatalogue_ID";
                dlparentcatalogue.DataTextField = "ParentCatalogue_Name";
                dlparentcatalogue.DataBind();
                for (int i = 0; i < dlparentcatalogue.Items.Count; i++)
                {
                    if (int.Parse(dlparentcatalogue.Items[i].Value) == ParentCatalogueID)
                    {
                        dlparentcatalogue.Items[i].Selected = true;
                    }
                }
                dlparentcatalogue_SelectedIndexChanged(source, e);
                dldetailproduct.EditItemIndex = 0;
                dldetailproduct.DataSource = ElectricDevice_BUS.DetailElectricDevice(Request.QueryString["ElectricDeviceID"]);
                dldetailproduct.DataBind();



            }
            if (e.CommandName == "btCancelProduct")
            {
                pncatalogue.Visible = false;
                dldetailproduct.EditItemIndex = -1;
                dldetailproduct.DataSource = ElectricDevice_BUS.DetailElectricDevice(Request.QueryString["ElectricDeviceID"]);
                dldetailproduct.DataBind();
            }
            if (e.CommandName == "btUpdateProduct")
            {
                Label lbelectricdevicename = (Label)e.Item.FindControl("lbelectricdevicename");

                TextBox tbRetailPrice = (TextBox)e.Item.FindControl("tbRetailPrice");
                TextBox tbDealerPrice = (TextBox)e.Item.FindControl("tbDealerPrice");
                DropDownList dlbrand = (DropDownList)e.Item.FindControl("dlbrand");
                DropDownList dlCurrency = (DropDownList)e.Item.FindControl("dlCurrency");
                TextBox tbquantity = (TextBox)e.Item.FindControl("tbquantity");
                TextBox tbquanlity = (TextBox)e.Item.FindControl("tbquanlity");
                TextBox tbsize = (TextBox)e.Item.FindControl("tbsize");
                TextBox tbdescriptionproduct = (TextBox)e.Item.FindControl("tbdescriptionproduct");
                FileUpload FileUpload1 = (FileUpload)e.Item.FindControl("FileUpload1");

                ELECTRIC_DEVICE electricdevice = new ELECTRIC_DEVICE();
                electricdevice.ElectricDevice_ID = lbelectricdevicename.Text;
                electricdevice.ElectricDevice_Name = lbelectricdevicename.Text;

                electricdevice.InsertedDate = DateTime.Now;
                electricdevice.NumberOfBuyers = 0;
                electricdevice.Quanlity = tbquanlity.Text;
                electricdevice.Status = 1;
                electricdevice.Size = tbsize.Text;
                electricdevice.Brand_ID = int.Parse(dlbrand.SelectedValue);
                electricdevice.ChildCatalogue_ID = int.Parse(dlchildrencatalogue.SelectedValue);
                electricdevice.Currency_ID = dlCurrency.SelectedValue;
                electricdevice.Description = tbdescriptionproduct.Text;
                try
                {
                    electricdevice.Quantity = int.Parse(tbquantity.Text);
                    electricdevice.RetailPrice = tbRetailPrice.Text;
                    electricdevice.DealerPrice = tbDealerPrice.Text;
                    electricdevice.Description = tbdescriptionproduct.Text;
                    electricdevice.ImagePath = null;
                    electricdevice.ModifiedDate = DateTime.Now;
                    if (checkFileType(FileUpload1.FileName, FileUpload1) && FileUpload1.PostedFile.FileName != "")  //Check for file types
                    {
                        FileInfo f = new FileInfo(FileUpload1.FileName);
                        string fileName;
                        //long lenght = f.Length;
                        if (FileUpload1.PostedFile.ContentLength < 50 * 1024)
                        {
                            fileName = electricdevice.ElectricDevice_ID + f.Extension;
                            electricdevice.ImagePath = fileName;
                            FileUpload1.SaveAs(MapPath("../images/" + fileName));

                        }
                        else
                        {
                            Alert.Show("Kích thước file phải nhỏ hơn 50kb !");
                        }
                    }
                    if (!checkFileType(FileUpload1.FileName, FileUpload1) && FileUpload1.PostedFile.FileName != "")
                    {
                        Alert.Show("Kiểu file không đúng. vui lòng upload file : .jpg , .gif, .png");
                    }
                    ParentCatalogueID = int.Parse(dlparentcatalogue.SelectedValue);
                    ChildCatalogueID = int.Parse(dlchildrencatalogue.SelectedValue);
                    ElectricDevice_BUS.UpdateElectricDevice(electricdevice);
                    Alert.Show("Cập nhật thành công !");
                    pncatalogue.Visible = false;
                    dldetailproduct.EditItemIndex = -1;
                    dldetailproduct.DataSource = ElectricDevice_BUS.DetailElectricDevice(Request.QueryString["ElectricDeviceID"]);
                    dldetailproduct.DataBind();
                }
                catch (Exception ex)
                {
                    Alert.Show("Vui lòng nhập số lượng và giá !");
                }


            }
            if (e.CommandName == "btDeleteProduct")
            {
                ElectricDevice_BUS.DeleteElectricDevice(Request.QueryString["ElectricDeviceID"]);

                string url = "Default.aspx";
                if (Request.QueryString["ParentCatalogueID"] != null)
                {
                    url = "DanhSachSanPham_Manager.aspx" + "?ParentCatalogueID=" + Request.QueryString["ParentCatalogueID"];
                }
                if (Request.QueryString["ChildCatalogueID"] != null)
                {
                    url = "DanhSachSanPham_Manager.aspx" + "?ChildCatalogueID=" + Request.QueryString["ChildCatalogueID"];
                }
                Alert.ShowAndRedirect("Đã xóa sản phẩm thành công !",url);
            }
        }

        private bool checkFileType(string fileName, FileUpload FileUpload1)
        {
            string fileExt = Path.GetExtension(FileUpload1.FileName);
            switch (fileExt.ToLower())
            {
                case ".png":
                    return true;
                case ".jpg":
                    return true;
                case ".gif":
                    return true;
                default:
                    return false;
            }

        }

        protected void dlparentcatalogue_SelectedIndexChanged(object sender, EventArgs e)
        {

            dlchildrencatalogue.DataSource = ChildCatalogue_BUS.ListCatalogue(int.Parse(dlparentcatalogue.SelectedValue));
            dlchildrencatalogue.DataTextField = "ChildCatalogue_Name";
            dlchildrencatalogue.DataValueField = "ChildCatalogue_ID";
            dlchildrencatalogue.DataBind();
            for (int i = 0; i < dlchildrencatalogue.Items.Count; i++)
            {
                if (int.Parse(dlchildrencatalogue.Items[i].Value) == ChildCatalogueID)
                {
                    dlchildrencatalogue.Items[i].Selected = true;
                }
            }
        }

        protected void dldetailproduct_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            DropDownList dlbrand = (DropDownList)e.Item.FindControl("dlbrand");
            if (dlbrand != null)
            {
                dlbrand.DataSource = Brand_BUS.ListBrand();
                dlbrand.DataTextField = "Brand_Name";
                dlbrand.DataValueField = "Brand_ID";
                dlbrand.DataBind();
                for (int i = 0; i < dlbrand.Items.Count; i++)
                {
                    if (int.Parse(dlbrand.Items[i].Value) == electricdevice.Brand_ID)
                    {
                        dlbrand.Items[i].Selected = true;
                    }
                }
            }

            DropDownList dlCurrency = (DropDownList)e.Item.FindControl("dlCurrency");
            if (dlCurrency != null)
            {
                dlCurrency.DataSource = ElectricDevice_BUS.GetCurrencyOfProduct();
                dlCurrency.DataValueField = "Currency_ID";
                dlCurrency.DataTextField = "Currency_Name";
                dlCurrency.DataBind();
                for (int i = 0; i < dlCurrency.Items.Count; i++)
                {
                    if (dlCurrency.Items[i].Value == electricdevice.Currency_ID)
                    {
                        dlCurrency.Items[i].Selected = true;
                    }
                }
            }

            if (e.Item.ItemType == ListItemType.Item)
            {
                string NonDiscountPrice = "";
                string DiscountPrice = "";

                Coupon_BUS.GetPriceCouponOfElectricDevice(Request.QueryString["ElectricDeviceID"], ref NonDiscountPrice, ref DiscountPrice);
                if (NonDiscountPrice != "" && DiscountPrice != "")
                {
                    Label lbDiscountPrice = (Label)e.Item.FindControl("lbDiscountPrice");
                    Label lbNonDiscountPrice = (Label)e.Item.FindControl("lbNonDiscountPrice");
                    lbDiscountPrice.Text = DiscountPrice;
                    lbNonDiscountPrice.Text = NonDiscountPrice;
                    e.Item.FindControl("divdel").Visible = true;
                    e.Item.FindControl("divnondel").Visible = false;
                }
                if (NonDiscountPrice == "" && DiscountPrice == "")
                {
                    e.Item.FindControl("divdel").Visible = false;
                    e.Item.FindControl("divnondel").Visible = true;
                }


            }

        }

        protected void ibBack_Click(object sender, ImageClickEventArgs e)
        {
            string url = "Default.aspx";
            if (Request.QueryString["ParentCatalogueID"] != null)
            {
                url = "DanhSachSanPham_Manager.aspx" + "?ParentCatalogueID=" + Request.QueryString["ParentCatalogueID"] + "&Name=" + Request.QueryString["Name"].ToString();
            }
            if (Request.QueryString["ChildCatalogueID"] != null)
            {
                url = "DanhSachSanPham_Manager.aspx" + "?ChildCatalogueID=" + Request.QueryString["ChildCatalogueID"] + "&Name=" + Request.QueryString["Name"].ToString();
            }
            Response.Redirect(url);
        }
    }
}
